import threading
import time
import os
import sys
import pymysql
from pythonTestDouyin.DouyinAutoSendBulletChat.autoSend import DouyinBulletChatBot
from pythonTestDouyin.DouyinAutoAcceptBulletChat.acceptBulletChat import DouyinLiveMonitor


class DouyinLiveRoomController:
    def __init__(self, db_config,live_id_path, live_id, wss_url):
        self.db_config = db_config
        self.live_id_path = live_id_path
        self.live_id = live_id
        self.wss_url = wss_url
        self.live_url = f"https://live.douyin.com/{live_id}"

        # 创建弹幕发送和接收实例
        self.bot = DouyinBulletChatBot(db_config, live_id_path)
        self.monitor = DouyinLiveMonitor(db_config,live_id,wss_url)

        # 控制线程状态
        self.running = True

        # 弹幕文件路径
        self.bullet_chat_file = r"C:\Users\a2038\Desktop\弹幕.txt"

    def start_monitor(self):
        """启动弹幕接收监控"""
        # 确保弹幕文件存在
        if not os.path.exists(self.bullet_chat_file):
            open(self.bullet_chat_file, 'w').close()

        self.monitor.start_monitoring()

    def start_bot(self):
        """启动弹幕发送机器人"""
        print("弹幕发送服务已启动...")
        self.bot.run()

    def display_status(self):
        """显示系统状态和控制选项"""
        while self.running:
            print("\n" + "=" * 50)
            print(f"直播间ID: {self.live_id}")
            print("1. 发送弹幕系统")
            print("2. 查看最新弹幕")
            print("3. 打开弹幕文件")
            print("4. 退出系统")
            print("=" * 50 + "\n")

            choice = input("请选择操作: ")

            if choice == '1':
                try:
                    bot_thread = threading.Thread(target=self.start_bot)
                    bot_thread.daemon = True
                    bot_thread.start()
                    bot_thread.join()
                except Exception as e:
                    print(self.monitor.now_to_date())
                    print(e)
            elif choice == '2':
                self.show_recent_messages()
            elif choice == '3':
                self.open_bullet_chat_file()
            elif choice == '4':
                self.shutdown()
                return

    def show_recent_messages(self):
        """显示最近的弹幕内容"""
        try:
            # 读取最后20行弹幕
            with open(self.bullet_chat_file, 'r', encoding='utf-8') as f:
                lines = f.readlines()[-20:]
                if not lines:
                    print("暂无弹幕记录")
                    return

                print("\n" + "=" * 50)
                print("最新弹幕记录:")
                for line in lines:
                    print(line.strip())
                print("=" * 50 + "\n")
        except Exception as e:
            print(f"读取弹幕文件失败: {e}")

    def open_bullet_chat_file(self):
        """打开弹幕文件"""
        try:
            if sys.platform == 'win32':
                os.startfile(self.bullet_chat_file)
            else:
                os.system(f'open "{self.bullet_chat_file}"')
            print("已打开弹幕文件")
        except Exception as e:
            print(f"打开文件失败: {e}")

    def shutdown(self):
        """关闭系统"""
        self.running = False
        print("正在关闭系统...")
        print(self.monitor.now_to_date())
        # 关闭弹幕接收
        if hasattr(self.monitor, 'ws') and self.monitor.ws:
            self.monitor.ws.close()

        # 关闭弹幕发送
        if hasattr(self.bot, 'browser') and self.bot.browser:
            self.bot.browser.quit()

        # 关闭数据库连接
        if hasattr(self.monitor, 'conn') and self.monitor.conn:
            self.monitor.conn.close()
        if hasattr(self.bot, 'conn') and self.bot.conn:
            self.bot.conn.close()

        print("系统已关闭")

    def run(self):
        """运行整个直播室控制器"""
        # 启动弹幕接收线程
        monitor_thread = threading.Thread(target=self.start_monitor)
        monitor_thread.daemon = True
        monitor_thread.start()

        print("弹幕接收服务已启动...")

        # 给监控一点时间初始化
        time.sleep(3)
        self.bot.start()
        print("浏览器服务已启动...")
        # 启动弹幕发送线程
        # bot_thread = threading.Thread(target=self.start_bot)
        # bot_thread.daemon = True
        # bot_thread.start()
        # print("弹幕发送服务已启动...")


        # 在主线程中显示控制菜单
        self.display_status()


if __name__ == '__main__':
    db_config = {
        "host": "localhost",
        "user": "root",
        "passwd": "root",
        "db": "ointment_interaction",
        "port": 3306
    }

    # 用户输入参数
    live_id_path = input("请输入直播间地址: ")
    live_id = input("请输入直播间ID: ")
    wss_url = input("请输入wss_url: ")

    # 创建并运行控制器
    controller = DouyinLiveRoomController(db_config,live_id_path ,live_id, wss_url)
    controller.run()